package cn.bbstone.pisces2.client.base;

import cn.bbstone.pisces2.client.handler.ClientHandler;
import cn.bbstone.pisces2.comm.codec.RspFileDecoder;
import cn.bbstone.pisces2.proto.rsp.RspFile;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * server response will dispatch to different client cmdHandler according stream prefix and cmd
 */
public class RspDispatcher {
    private static Logger log = LoggerFactory.getLogger(RspDispatcher.class);

    public static void dispatch(ChannelHandlerContext ctx, ByteBuf msg) {
        RspFileDecoder decoder = new RspFileDecoder();
        RspFile rspFile = null;
        try {
            rspFile = decoder.decode(msg);
        } catch (Exception e) {
            log.error("decode response msg error.", e);
        }
        Byte msgType = rspFile.getMsgType();
//        log.info("recv {} response", HexUtil.toHex(msgType));
        ClientHandler clientHandler = ClientCmdRegister.getHandler(msgType);
        if (clientHandler == null) {
            log.error("not found cmdHandler for msgType: {}, please register first.", msgType);
            return;
        }
        clientHandler.handle(ctx, rspFile);
    }

}
